package cn.shop.dys.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONObject;

import java.util.List;

import cn.shop.dys.R;
import cn.shop.dys.adapter.Category1Adapter;
import cn.shop.dys.bean.Category;
import cn.shop.dys.constant.CommonConstant;


/**
 * Created by Administrator on 2016/4/21.
 */
public class ProductRelativeFragment extends Fragment {

    private ListView lvRelative;
    private int pId;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_product_relative, container,false);
        lvRelative = (ListView) view.findViewById(R.id.lv_relative);
        pId = getActivity().getIntent().getIntExtra("pId", 1) / 10;
        requestData();

        return view;
    }

    private void requestData() {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.product_CATEGORY, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String jsonCategory = jsonObject.getString("category");
                    Gson gson = new Gson();
                    List<Category> categorys = gson.fromJson(jsonCategory, new TypeToken<List<Category>>() {
                    }.getType());
                    for (int i = categorys.size() - 1; i >= 0; i--) {
                        int t = categorys.get(i).getId() / 10;
                        if (t != pId) {
                            categorys.remove(i);
                        }
                    }
                    Category1Adapter categoryAdapter = new Category1Adapter(getActivity(), categorys);
                    lvRelative.setAdapter(categoryAdapter);
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });

    }
}

